import 'package:flutter/material.dart';
import 'pen_style.dart';

import 'pen.dart';

/// 橡皮擦
class EraserPen extends BasePen {
  Paint linePaint; //对应描边,线条,图片的画笔

  /// 线条参数
  Path path = Path(); //线条的路径

  /// 绘制过程所需参数
  ScrawlPoint prePoint, currentPoint; //滑动最后的点和当前绘制的点

  final PenStyle style;
  final String brushId;

  EraserPen({
    @required this.brushId,
    @required this.style,
  }) {
    Color colorLine = Colors.black;
    linePaint = Paint()
      ..isAntiAlias = true
      ..strokeJoin = StrokeJoin.round
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke
      ..color = colorLine
      ..strokeWidth = style.lineWidth * 1.0
      ..blendMode = BlendMode.clear;
  }

  @override
  void draw(Canvas canvas, {bool isRedraw = false}) {
    //撤销或恢复操作
    if (path != null) {
      canvas.drawPath(path, linePaint);
    }
  }

  @override
  bool downEvent(Offset touchPoint) {
    double x = touchPoint.dx;
    double y = touchPoint.dy;
    path.moveTo(x, y);
    prePoint = ScrawlPoint(x: x, y: y);
    return true;
  }

  @override
  bool moveEvent(Offset touchPoint) {
    ScrawlPoint point;
    bool isChanged = false;

    double x = touchPoint.dx;
    double y = touchPoint.dy;
    final double dx = (x - prePoint.x).abs();
    final double dy = (y - prePoint.y).abs();
    //两点之间的距离大于等于3时，生成贝塞尔绘制曲线
    if (dx >= 3 || dy >= 3) {
      //设置贝塞尔曲线的操作点为起点和终点的一半
      double cX = (x + prePoint.x) / 2;
      double cY = (y + prePoint.y) / 2;

      //二次贝塞尔，实现平滑曲线；preX, preY为操作点，cX, cY为终点
      path.quadraticBezierTo(prePoint.x, prePoint.y, cX, cY);
      point = ScrawlPoint(x: x, y: y);
      isChanged = true;
    }
    if (point != null) {
      prePoint = point;
    }
    if (isChanged) {
      return true;
    } else {
      return false;
    }
  }

  @override
  bool upEvent(Offset touchPoint) {
    return true;
  }

  @override
  String getBrushId() {
    return brushId;
  }
}
